package page;

import java.util.List;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;

import app.WebApp;
import dao.DispatcherDao;
import entity.Dispatcher;

public class DispatcherLoginPage extends WebPage {
	
	public DispatcherLoginPage(){
		super();
		final Dispatcher dispatcher = new Dispatcher();
		final Form<Dispatcher> form = new Form<Dispatcher>("form", new CompoundPropertyModel<Dispatcher>(dispatcher));
		add(form);
		form.add(new TextField<String>("login"));
		form.add(new TextField<String>("password"));
		form.add(new SubmitLink("loginButton") {
			@Override
			public void onSubmit() {
				if(dispatcher.getLogin()==null || dispatcher.getPassword()==null){
					setResponsePage(new DispatcherLoginPage());
				}
				else{
					final DispatcherDao dispatcherDao = new DispatcherDao(WebApp.DATA_XML_FOLDER);
					final List<Dispatcher> dispatchers = dispatcherDao.getAll();
					if(dispatchers.size()==0){
						Dispatcher newDispatcher = new Dispatcher();
						newDispatcher.setLogin("dispatcher");
						newDispatcher.setPassword("dispatcher");
						dispatcherDao.saveNew(newDispatcher);
					}
					final List<Dispatcher> allDispatchers = dispatcherDao.getAll();
					for(final Dispatcher row:allDispatchers){
						if(dispatcher.getLogin().equals(row.getLogin()) && dispatcher.getPassword().equals(row.getPassword())){
							setResponsePage(new DispatcherFlightListPage());
							break;
						}
						else setResponsePage(new DispatcherLoginPage());
					}
				}
				
			}
		});
		form.add(new SubmitLink("cancel") {
			@Override
			public void onSubmit() {
				setResponsePage(new AllFlightListPage());
			}
		});
	};		
}


